<template>
  <a-layout class="home-layout">
    <a-layout-sider class="home-layout-sider" theme="light" >
      <draggable tag="ul" :list="components" class="widget-option-list"
        v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
        @start="handleMoveStart"
        @end="handleMoveEnd"
      >
        <li v-for="element in components" :key="element.type" :data-type="element.name">
          <div class="widget-option-item">
            <i class="icon iconfont" :class="element.icon"></i>
            <span class="label">{{ element.name }}</span>
          </div>
        </li>
      </draggable>
      <draggable tag="ul" :list="layoutComponents" class="widget-option-list"
        v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
        @start="handleMoveStart"
        @end="handleMoveEnd"
      >
        <li v-for="element in layoutComponents" :key="element.type" :data-type="element.name">
          <div class="widget-option-item" >
            <i class="icon iconfont" :class="element.icon"></i>
            <span class="label">{{ element.name }}</span>
          </div>
        </li>
      </draggable>
    </a-layout-sider>
    <a-layout-content class="home-layout-content">
      <a-layout-header>
        <div>
        <a-input v-model="formName" style="width: 200px" />
        <a-button type="primary" @click="handlePreview">预览</a-button>
        <a-button type="primary" @click="handleGenerateJson">生成JSON</a-button>
        <a-button type="primary" @click="handleUpload">导入JSON</a-button>
        <a-button @click="handleClear">清除</a-button>
        <a-button type="primary" @click="handleSave">保存</a-button>
        </div>
      </a-layout-header>
      <a-layout-content>
        <widget-form :data="widgetObj" :select.sync="widgetSelect" />
      </a-layout-content>
    </a-layout-content>
    <a-layout-sider class="widget-config-container" theme="light" width="300">
      <widget-config :data="widgetSelect"/>
    </a-layout-sider>
    <custom-dialog :visible.sync="previewVisible" width="1200px" title="预览">
      <generate-form ref="generateForm" v-if="previewVisible" :data="previewWidget" @change="handleChange" />
      <template slot="action">
        <a-button type="primary" @click="handleTest">获取数据</a-button>
      </template>
    </custom-dialog>
    <custom-dialog :visible.sync="jsonVisible" width="800px" title="生成JSON" :destroyOnClose="true">
      <div id="jsoneditor" style="height: 400px;width: 100%;">{{jsonTemplate}}</div>
      <template slot="action">
        <a-button type="primary" class="copy-btn" :data-clipboard-text="jsonCopyValue">复制JSON</a-button>
      </template>
    </custom-dialog>
    <custom-dialog :visible.sync="uploadVisible" width="800px" title="导入JSON" :destroyOnClose="true">
      <div id="uploadeditor" style="height: 400px;width: 100%;">{{jsonEg}}</div>
      <template slot="action">
        <a-button type="primary" @click="handleUploadJson">OK</a-button>
      </template>
    </custom-dialog>
  </a-layout>
</template>

<script>
import draggable from "vuedraggable";
import Clipboard from 'clipboard';
import CustomDialog from './CustomDialog.vue';
import GenerateForm from './GenerateForm.vue';
import WidgetConfig from './WidgetConfig.vue';
import WidgetForm from './WidgetForm.vue';
import {components, layoutComponents} from '../config/componentsConfig';
// import ace from 'ace-builds/src-min-noconflict/ace'
export default {
  name: "Container",
    components: {
    draggable,
    WidgetForm,
    WidgetConfig,
    CustomDialog,
    GenerateForm,
  },
  data() {
    return {
      components,
      layoutComponents,
      formName: '',
      widgetObj: {
        list: []
      },
      widgetSelect: null,
      previewVisible: false,
      previewData: null,
      jsonVisible: false,
      jsonTemplate: '',
      jsonClipboard: null,
      jsonCopyValue: '',
      uploadVisible: false,
      uploadEditor: null,
      jsonEg: `{
  "list": []
}`,
    };
  },
  props: {
    formId: {
      type: String,
      default: '',
    },
    widgetData: {
      type: String,
      default: '{"list": []}',
    },
    templeteName: {
      type: String,
      default: '',
    }
  },
  watch: {
    widgetData: function(val) {
      if (val) {
        this.setFormData(JSON.parse(this.widgetData))
      } else {
        this.handleClear();
      }
    },
    templeteName: function(val) {
      this.formName = val || "";
    }
  },
  created(){},
  mounted(){
    this.loadJs('https://cdn.bootcdn.net/ajax/libs/ace/1.4.9/ace.js')
  },
  methods: {
    loadJs(url){
      const script = document.createElement('script');
      script.type="text/javascript";
      script.src = url;
      document.body.appendChild(script);
    },
    handleMoveStart ({oldIndex}) {
      oldIndex
      // console.log('start', oldIndex, this.components)
    },
    handleMoveEnd (evt) {
      evt
      // console.log('end', evt)
    },
    handlePreview() {
      this.previewWidget = JSON.parse(JSON.stringify(this.widgetObj))
      this.previewVisible = true;
    },
    handleChange(key, val, models) {
      console.log(key, val, models);
    },
    async handleTest(){
      try {
        const result = await this.$refs['generateForm'].getData();
        this.$info({
          title: 'Data',
          content: JSON.stringify(result),
          onOk() {},
        });
      } catch (error) {
        console.log(error);
      }
    },
    handleGenerateJson() {
      this.jsonVisible = true;
      this.jsonTemplate = this.widgetObj;
      this.$nextTick(() => {
        if (window.ace) {
          window.ace.edit('jsoneditor').session.setMode("ace/mode/json");
        }
        if (!this.jsonClipboard) {
          this.jsonClipboard = new Clipboard('.copy-btn')
          this.jsonClipboard.on('success', () => {
            this.$message.success('已复制')
          })
        }
        this.jsonCopyValue = JSON.stringify(this.jsonTemplate)
      })
    },
    handleUpload(){
      this.uploadVisible = true
      this.$nextTick(() => {
        if (window.ace) {
          this.uploadEditor = window.ace.edit('uploadeditor')
          this.uploadEditor.session.setMode("ace/mode/json")
        }
      })
    },
    handleUploadJson () {
      try {
        this.setFormData(JSON.parse(this.uploadEditor.getValue()))
        this.uploadVisible = false
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    setFormData(widgetJSON) {
      this.widgetObj = widgetJSON;
      if (widgetJSON.list.length > 0) {
        this.widgetSelect = widgetJSON.list[0]
      }
    },
    handleClear(){
      this.widgetObj = {
        list: [],
      };
      this.widgetSelect = null;
    },
    handleSave() {
      this.$emit('save', { id: this.formId, name: this.formName, formTemplete: JSON.stringify(this.widgetObj)})
    }
  }
};
</script>
